package com.ndkj.blog.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @program: Blog
 * @description: MVC-config
 * @author: liuyong
 * @create: 2021-09-23 17:24
 */
@Configuration
public class MvcConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/login.html").setViewName("index");
    }

    /**
     * 注册拦截器使拦截器生效,这里需要传入一个自定义的继承HandlerInterceptor接口的拦截器实现类
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //addPathPatterns("/**")拦截所有的访问请求 excludePathPatterns：排除的不拦截访问请求
        registry.addInterceptor(new LoginHandlerInterceptor())
                .addPathPatterns("/admin/**").excludePathPatterns("/admin");
    }

    /**
     * 跨域配置
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedHeaders("*")
                .allowedMethods("*")
                .maxAge(1800)
                .allowedOrigins("*");
    }
}
